package cc.rengu.igas.share.core.service.channel.cups;

import cc.rengu.igas.channel.cups.facade.base.Header;
import cc.rengu.igas.channel.cups.facade.bean.CupsTermInfo;
import cc.rengu.igas.channel.cups.facade.request.ConsumeRequest;
import cc.rengu.igas.channel.cups.facade.response.ConsumeResponse;
import cc.rengu.igas.channel.cups.facade.result.Result;
import cc.rengu.igas.share.common.constant.ShareParamConstant;
import cc.rengu.igas.share.common.constant.ShareServiceConstant;
import cc.rengu.igas.share.core.model.MchntInfo;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.oltp.service.base.ChannelBaseService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.entity.PayOrderInfo;
import cc.rengu.oltp.service.common.enums.*;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.OrderInfo;
import cc.rengu.oltp.service.model.TxnInfo;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.*;
import com.alibaba.fastjson.JSON;

import java.util.*;

/**
 * CUPS消费
 * Created by lzl on 2021/4/23 11:08
 */
public class CupsConsumeService extends ChannelBaseService {
    @Override
    public Object callPreProc(TxnInfo txnInfo, ChannelCallCfg channelCallCfg, OrderInfo orderInfo) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        Header cupsHeader = new Header();
        cupsHeader.setInstId(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.INST_ID));
        cupsHeader.setChanlId(channelCallCfg.getMsgSrcId());
        cupsHeader.setSrcSysId(AppParamConstant.SYS_ID);
        cupsHeader.setBizType(AppParamConstant.DEFAULT_BIZ_TYPE);
        cupsHeader.setVersion(ShareParamConstant.DUBBO_VSERSION);
        cupsHeader.setTxnNum(channelCallCfg.getCallChannelTxn());
        cupsHeader.setTraceNo(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM) + channelCallCfg.getCallIndex());
        cupsHeader.setTransTime(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_TIME));
        cupsHeader.setTransDate(xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.TRANS_DATE));
        ConsumeRequest consumeRequest = new ConsumeRequest();
        ConvertUtil.convertOutput(consumeRequest);
        consumeRequest.setHeader(cupsHeader);

        MchntService mchntService = new MchntServiceImpl();
        MchntInfo mchntInfo = mchntService.getMchntInfo(consumeRequest.getHeader().getInstId(), xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.MCHNT_NO));
        String sysNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);

        consumeRequest.setCupsTraceNo(sysNum.substring(sysNum.length() - 6));
        consumeRequest.setTransDateTime(cupsHeader.getTransDate().substring(4, 8) + cupsHeader.getTransTime());
        consumeRequest.setTermNo(xmlTreeUtil.getXmlTreeStringValue("termNo"));
        consumeRequest.setMchntShortName(mchntInfo.getMchntSimpleName());
        consumeRequest.setMchntType(mchntInfo.getIndustryType());
        consumeRequest.setCupsMchntNo(xmlTreeUtil.getXmlTreeStringValue("mchntNo"));
        consumeRequest.setCupsInstCode(mchntInfo.getCupsInstId());
        consumeRequest.setFwdInstCode(consumeRequest.getCupsInstCode());
        consumeRequest.setOrderAmt(orderInfo.getUserOrderInfo().getRealPayAmt());
        consumeRequest.setOrderCcy(AppParamConstant.DEFAULT_ORDER_CCY);
        consumeRequest.setPayAcctNo(xmlTreeUtil.getXmlTreeStringValue("cardNo"));
        String newPin = xmlTreeUtil.getXmlTreeStringValue("newPin");
        /*小额免密标志  密码*/
        if (StringUtil.isEmptyOrNull(newPin)) {
            rglog.debug("小额免密标志：<{}>", mchntInfo.getNoPasswordFlag());
            consumeRequest.setNoPinFlag(mchntInfo.getNoPasswordFlag());
        } else {
            consumeRequest.setNoPinFlag(mchntInfo.getNoPasswordFlag());
            consumeRequest.setPinData(newPin);
        }
        consumeRequest.setTrack2Data(xmlTreeUtil.getXmlTreeStringValue("secTractinf"));
        consumeRequest.setTrack3Data(xmlTreeUtil.getXmlTreeStringValue("thdTractinf"));
        consumeRequest.setReferenceNo(xmlTreeUtil.getXmlTreeStringValue("refNo"));
        consumeRequest.setCardExpireDate(xmlTreeUtil.getXmlTreeStringValue("expDate"));
        consumeRequest.setEntryMode(xmlTreeUtil.getXmlTreeStringValue("posEntryModeCode"));
        consumeRequest.setCardSeqNo(xmlTreeUtil.getXmlTreeStringValue("cardSeqid"));
        /*区分磁条卡 与 芯片卡*/
        if ("021".equals(xmlTreeUtil.getXmlTreeStringValue("posEntryModeCode"))) {
            /*55域 卡数据*/
            consumeRequest.setIcData(StringUtil.leftFillZero("0", 509));
            /*卡 数据长度*/
            consumeRequest.setIcDataLength("0");
        } else {
            /*55域 卡数据*/
            consumeRequest.setIcData(xmlTreeUtil.getXmlTreeStringValue("iccData"));
            /*卡 数据长度*/
            consumeRequest.setIcDataLength(xmlTreeUtil.getXmlTreeStringValue("iccardDatalen"));
        }
        consumeRequest.setIcConCode(xmlTreeUtil.getXmlTreeStringValue("posCondCode"));
        consumeRequest.setSecCtrlInfo(xmlTreeUtil.getXmlTreeStringValue("secTractinf"));
        CupsTermInfo cupsTermInfo = new CupsTermInfo();
        cupsTermInfo.setLatitude(xmlTreeUtil.getXmlTreeStringValue("termInfo/latitude"));
        cupsTermInfo.setLongitude(xmlTreeUtil.getXmlTreeStringValue("termInfo/longitude"));
        cupsTermInfo.setNetworkLicense(xmlTreeUtil.getXmlTreeStringValue("termInfo/networkLicense"));
        cupsTermInfo.setDeviceType(xmlTreeUtil.getXmlTreeStringValue("termInfo/deviceType"));
        cupsTermInfo.setSerialNum(xmlTreeUtil.getXmlTreeStringValue("termInfo/serialNum"));
        cupsTermInfo.setEncryptRandNum(xmlTreeUtil.getXmlTreeStringValue("termInfo/encryptRandNum"));
        cupsTermInfo.setSecretText(xmlTreeUtil.getXmlTreeStringValue("termInfo/secretText"));
        cupsTermInfo.setAppVersion(xmlTreeUtil.getXmlTreeStringValue("termInfo/appVersion"));
        consumeRequest.setTermInfo(cupsTermInfo);
        /*设置保留域*/
        Map map = new HashMap();
        map.put("branchId", "866777777");
        map.put("globalTraceNum", " ");
        map.put("globalPathNum", " ");
        String acqReserved = JSON.toJSONString(map);
        consumeRequest.setAcqReserved(acqReserved);
        rglog.debug("CUPS消费请求:<{}>", JSON.toJSONString(consumeRequest));
        return consumeRequest;
    }

    @Override
    public PayOrderInfo generatePayOrderInfo(ChannelCallCfg channelCallCfg, OrderInfo orderInfo, Object request) throws Exception {
        PayOrderInfo payOrderInfo = new PayOrderInfo();
        ConsumeRequest consumeRequest = (ConsumeRequest) request;
        BeanUtil.beanCopy(orderInfo.getUserOrderInfo(), payOrderInfo);
        if (orderInfo.getMchntOrderInfoList().size() == 1) {
            payOrderInfo.setMchntNo(orderInfo.getMchntOrderInfoList().get(0).getMchntNo());
        } else {
            payOrderInfo.setMchntNo(orderInfo.getUserOrderInfo().getGroupMchntNo());
        }
        payOrderInfo.setTxnNum(channelCallCfg.getTxnNum());
        payOrderInfo.setBizType(channelCallCfg.getBizType());
        payOrderInfo.setSysSeqNum(orderInfo.getUserOrderInfo().getSysSeqNum());
        payOrderInfo.setOrderCcy(orderInfo.getUserOrderInfo().getOrderCcy());
        payOrderInfo.setMsgDstId(channelCallCfg.getCallChannelId());
        payOrderInfo.setDstCallIndex(channelCallCfg.getCallIndex());
        payOrderInfo.setChannelSeqNum(Objects.requireNonNull(consumeRequest).getHeader().getTraceNo());
        payOrderInfo.setChannelReconKey(consumeRequest.getHeader().getTraceNo());
        payOrderInfo.setDstTxnNum(channelCallCfg.getCallChannelTxn());
        payOrderInfo.setPayType(PayTypeEnum.OTHER_BANK_CARD.getPayType());
        payOrderInfo.setPayerAcctType(AcctTypeEnum.ALL.getAcctType());
        payOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
        payOrderInfo.setTransStatus(TransStatusEnum.TRANS_INIT.getStatus());
        payOrderInfo.setCreateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        payOrderInfo.setUserId(orderInfo.getUserOrderInfo().getUserId());
        return payOrderInfo;
    }

    @Override
    public Object callProc(ChannelCallCfg channelCallCfg, Object request) throws Exception {
        ConsumeRequest consumeRequest = (ConsumeRequest) request;
        /* Step1：调用接口，获取结果 */
        Result<ConsumeResponse> callResult;
        DubboService dubboService = new DubboServiceImpl();
        if (AppParamConstant.YES.equals(channelCallCfg.getSyncCallFlag())) {
            /* Step1.1：异步调用 */
            int iReturnCode;
            int callTimes = 0 == channelCallCfg.getSyncQueryRepeatNum() ? 1 : channelCallCfg.getSyncQueryRepeatNum();
            int gatTime = channelCallCfg.getSyncQueryRepeatTime();
            int gatType = StringUtil.isEmptyOrNull(channelCallCfg.getSyncQueryGapType()) ? 0 : Integer.parseInt(channelCallCfg.getSyncQueryGapType());
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.1：异步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.CUPS_SERVICE_INNER_PATH);
                iReturnCode = dubboService.asynCallDubboInnerMethod(clasz, ShareServiceConstant.CUPS_CONSUME_METHOD, consumeRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.1.2：异步远程调用 */
                iReturnCode = dubboService.asynCallDubboService(ShareServiceConstant.CUPS_SERVICE, ShareServiceConstant.CUPS_CONSUME_METHOD, consumeRequest, channelCallCfg.getSyncResultServiceName(), callTimes, gatType, gatTime);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
            if (0 == iReturnCode) {
                return new BizResponse<>(OltpRpcdEnum.TRANS_SUCCESS.getRespCode(), OltpRpcdEnum.TRANS_SUCCESS.getRespDesc());
            } else {
                return new BizResponse<>(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
            }
        } else {
            /* Step1.2：同步调用 */
            if (ChannelCallModeEnum.LOCAL.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.1：同步应用内调用 */
                Class clasz = Class.forName(ShareServiceConstant.CUPS_SERVICE_INNER_PATH);
                callResult = (Result<ConsumeResponse>) dubboService.callDubboInnerMethod(clasz, ShareServiceConstant.CUPS_CONSUME_METHOD, consumeRequest);
            } else if (ChannelCallModeEnum.REMOTE.getMode().equals(channelCallCfg.getChannelCallMode())) {
                /* Step1.2.2：同步远程调用 */
                callResult = (Result<ConsumeResponse>) dubboService.callDubboService(ShareServiceConstant.CUPS_SERVICE, ShareServiceConstant.CUPS_CONSUME_METHOD, consumeRequest);
            } else {
                rglog.error("不支持的通道服务调用方式:{}，交易拒绝!", channelCallCfg.getChannelCallMode());
                throw new BizException(OltpRpcdEnum.CALL_BIZ_SERVICE_ERROR);
            }
        }
        return callResult;
    }

    @Override
    public Object querySyncCallResult(PayOrderInfo payOrderInfo, Object request) {
        return null;
    }

    @Override
    public OrderInfo callResultOrderProc(OrderInfo orderInfo, String payOrderIndex, TransStatusEnum transStatusEnum, Object response) {
        OrderInfo updateOrderInfo = new OrderInfo();
        Result<ConsumeResponse> callResult = (Result<ConsumeResponse>) response;
        Optional<PayOrderInfo> payOrderInfoOpt = orderInfo.getPayOrderInfoList().stream().filter(item -> item.getDstCallIndex().equals(payOrderIndex)).findFirst();
        if (payOrderInfoOpt.isPresent() && null != callResult && null != callResult.getResult()) {
            ConsumeResponse consumeResponse = callResult.getResult();
            PayOrderInfo payOrderInfo = payOrderInfoOpt.get();
            payOrderInfo.setTransStatus(transStatusEnum.getStatus());
            payOrderInfo.setRespCode(consumeResponse.getRespCode());
            payOrderInfo.setRespDesc(consumeResponse.getRespDesc());
            payOrderInfo.setUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            switch (transStatusEnum) {
                case TRANS_SUCC:
                    payOrderInfo.setBizStatus(BizStatusEnum.FINISH.getStatus());
                    /* 用户订单信息处理 */
                    updateOrderInfo.setUserOrderInfo(orderInfo.getUserOrderInfo());
                    /* 商户订单信息处理 */
                    payOrderInfo.setSettleDate(DateUtil.getCurrentDate());

                    break;
                case TRANS_TIMEOUT:
                    payOrderInfo.setBizStatus(BizStatusEnum.PROCESSING.getStatus());
                    break;
                case SYSTEM_REJECT:
                    payOrderInfo.setBizStatus(BizStatusEnum.FAILED.getStatus());
                    break;
                default:
                    break;
            }
            List<PayOrderInfo> payOrderInfoList = new ArrayList<>();
            payOrderInfoList.add(payOrderInfo);
            updateOrderInfo.setPayOrderInfoList(payOrderInfoList);
        }
        return updateOrderInfo;
    }
}
